<template>
  <div class="view-fill">
    <div v-if="!modifyInfo.visible" class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        @returnBack="$emit('returnBack')"
      >
        <template v-slot:full-button>
          <el-button
            v-if="
              $permission('withTableOrder:submit') && infoList.data.status === 1
            "
            @click="submit"
            >提交</el-button
          >
          <el-button
            v-if="
              $permission('withTableOrder:update') && infoList.data.status === 1
            "
            @click="update"
            >修改</el-button
          >
          <el-button
            v-if="
              $permission('withTableOrder:ratify') && infoList.data.status === 2
            "
            @click="ratify"
            >批准</el-button
          >
          <el-button
            v-if="
              $permission('withTableOrder:reject') && infoList.data.status === 2
            "
            @click="reject"
            >驳回</el-button
          >
          <el-button
            v-if="
              $permission('withTableOrder:revoke') && infoList.data.status === 2
            "
            @click="revoke"
            >撤回</el-button
          >
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="canPrint"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <!-- <el-button
            v-if="$permission('withTableOrder:printOrderDetail')"
            @click="print"
            >打印</el-button
          > -->
          <el-button
            v-if="$permission('withTableOrder:excelOrderDetail')"
            @click="exportExcel"
            >导出excel</el-button
          >
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="infoList"></basic-information>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>订单包详情</p>
          </div>
          <div class="model-panel-body">
            <div class="layui-card-body">
              <!-- 表格 -->
              <page-table
                v-model:data="withTableKitTableInfo.data"
                :pager="false"
                :field-list="withTableKitTableInfo.fieldList"
                :check-box="false"
                :tab-index="true"
              >
                <template v-slot:col-code="scope">
                  <span class="slip-edit" @click="showDetail(scope.row)">{{
                    scope.row.code || '-'
                  }}</span>
                </template>
              </page-table>
            </div>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>订单产品明细</p>
          </div>
          <div class="model-panel-body">
            <div class="layui-card-body">
              <!-- 表格 -->
              <page-table
                v-model:data="tableInfo.data"
                :pager="false"
                :field-list="tableInfo.fieldList"
                :check-box="false"
                :tab-index="true"
              >
              </page-table>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <!-- 修改 -->
    <Modify
      v-if="modifyInfo.visible"
      :order-id="modifyInfo.orderId"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      @returnModify="returnModify"
    />
    <WithTableKitDetail
      v-if="withTableKitInfo.visible"
      v-model:show-dialog="withTableKitInfo.visible"
      :query="withTableKitInfo.query"
      table-key="withTableOrderDetailKitProduct-com.slip.spd.entity.vo.withtable.WithTableOrderKitDetailVO"
    />
  </div>
</template>

<script setup name="details">
import BasicInformation from '@/components/BasicInformation/index'
import PageTable from '@/components/PageTable/index'
import WithTableKitDetail from './withTableKitDetail'
import Modify from './modify'
import { getCustomizeSetting } from '@/api/customize'
import {
  getWithTableOrderById,
  getWithTableOrderKitAll,
  getWithTableOrderKitDetailAll,
  withTableOrderRatify,
  withTableOrderRejecty,
  withTableOrderSubmit,
  withTableOrderRevoke,
  withTableOrderPrintOrder,
  withTableOrderExcelOrder,
} from '@/api/withTable.js'
import { fatchTemplateByCode } from '@/api/base'
import { orderOpAffairAll } from '@/api/affair'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const props = defineProps(['visible', 'id'])

const title = ref('跟台订单详情')
const infoList = reactive({
  data: {},
  fieldList: [
    {
      label: '单号',
      value: 'orderNo',
    },
    {
      label: '部门',
      value: 'deptName',
    },
    {
      label: '供应商',
      value: 'supplierName',
    },
    {
      label: '状态',
      value: 'statusValue',
    },
    { label: '创建人', value: 'createUserName', type: 'text' },
    { label: '创建时间', value: 'createTime', type: 'text' },
    { label: '更新人', value: 'updateUserName', type: 'text' },
    { label: '更新时间', value: 'updateTime', type: 'text' },
    {
      label: '备注',
      value: 'remark',
      type: 'popover',
    },
  ],
})
const tableInfo = reactive({
  data: [],
  fieldList: [],
})
const withTableKitTableInfo = reactive({
  data: [],
  fieldList: [],
})
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
    queryParams: {},
  },
})
const withTableKitFilterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
    queryParams: {},
  },
})
const withTableKitInfo = reactive({
  visible: false,
  query: {
    orderKitId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: '',
    },
  },
})
const affairTableInfo = reactive({
  api: orderOpAffairAll,
  query: {
    orderType: 79,
    orderId: props.id,
    sort: 'operate_time desc',
  },
})
const modifyInfo = reactive({
  visible: false,
  orderId: '',
  title: '修改跟台订单',
})
const isNotEmptyString = ref('')

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
const canPrint = computed(() => {
  return proxy.$permission('withTableOrder:printOrderDetail')
})
const canPrintQrCode = computed(() => {
  return (
    proxy.$permission('withTableOrder:printCode') &&
    (infoList.data.status === 2 || infoList.data.status === 3)
  )
})
let obj = {
  code: {
    label: '编码',
    value: 'code',
    componentType: 'input',
    type: 'slot',
    show: false,
    hidden: true,
  },
  name: {
    label: '名称',
    value: 'name',
    componentType: 'input',
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
})
withTableKitTableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()
getWithTableKitCustomize()

function showDetail(row) {
  withTableKitInfo.query.orderKitId.value = row.id
  withTableKitInfo.visible = true
}
function ifRenderValue(row) {
  return (
    row.codeType !== 1 &&
    (infoList.data.status === 2 || infoList.data.status === 3)
  )
}
function update() {
  modifyInfo.visible = true
  modifyInfo.orderId = props.id
}
//提交
function submit() {
  withTableOrderSubmit([props.id]).then((res) => {
    if (res && res.success) {
      returnModify()
    }
  })
}
//撤回
function revoke() {
  withTableOrderRevoke([props.id]).then((res) => {
    if (res && res.success) {
      returnModify()
    }
  })
}
function ratify() {
  //批准
  const params = {
    ids: [props.id],
    ratifyReason: '',
  }
  saveRatify(params)
}
function saveRatify(params) {
  withTableOrderRatify(params).then((res) => {
    if (res && res.success) {
      returnModify()
    }
  })
}
function reject() {
  //驳回
  proxy
    .$prompt('请输入驳回理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: isNotEmptyString.value,
      inputErrorMessage: '请输入驳回理由',
    })
    .then(({ value }) => {
      const params = {
        ids: [props.id],
        rejectReason: value,
      }
      withTableOrderRejecty(params).then((res) => {
        if (res && res.success) {
          returnModify()
        }
      })
    })
}
//导出excel
async function exportExcel() {
  withTableOrderExcelOrder(withTableKitFilterInfo.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'withTableOrderKitDetail',
    deptId: infoList.data.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            orderId: props.id,
          },
          callback: printCallback,
          data: {},
        })
      }
    }
  })
}
function printCallback() {
  try {
    // 打印成功增加打印次数
    updatePrintCount({
      orderNo: infoList.data.orderNo,
      orderId: props.id,
      orderType: 79,
    })
  } catch (error) {}
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      orderId: props.id,
    },
    callback: printCallback,
    data: {},
  })
  popoverVisible.value = false
}
function getPrintData(temp) {
  let infoListData = infoList.data
  let params = {
    tableKey:
      infoListData.acceptOrderNo && infoListData.acceptOrderId
        ? ''
        : 'withTableOrderDetail-com.slip.spd.entity.vo.withtable.WithTableRecordOrderDetailVO',
    orderIds: [props.id],
  }
  withTableOrderPrintOrder(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
function getList() {
  getWithTableOrderKitDetailAll(filterInfo.query).then((resp) => {
    if (resp && resp.success) {
      tableInfo.data = resp.data
    }
  })
}
function getWithTableKitList() {
  getWithTableOrderKitAll(withTableKitFilterInfo.query).then((resp) => {
    if (resp && resp.success) {
      withTableKitTableInfo.data = resp.data
    }
  })
}

function getMain() {
  getWithTableOrderById(props.id).then((resp) => {
    if (resp && resp.success) {
      infoList.data = resp.data
    }
  })
}
function returnModify() {
  getMain()
  getList()
  getWithTableKitList()
}
function getCustomize() {
  let param = {
    tableKey:
      'withTableOrderDetailProduct-com.slip.spd.entity.vo.withtable.WithTableOrderKitDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      let obj = proxy.$fn.setFieldList(tableInfo.fieldList, data.detail, true)
      tableInfo.fieldList = obj.fieldList
      getList()
      getMain()
    }
  })
}
function getWithTableKitCustomize() {
  let tableInfo = withTableKitTableInfo
  let param = {
    tableKey:
      'withTableOrderDetail-com.slip.spd.entity.vo.withtable.WithTableOrderKitVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      withTableKitFilterInfo.query.customizeUserVO = data
      let obj = proxy.$fn.setFieldList(tableInfo.fieldList, data.detail, true)
      tableInfo.fieldList = obj.fieldList
      getWithTableKitList()
    }
  })
}
</script>

<style scoped></style>
